const { user, order, vip_grade, user_note_recharge } = require("../../middleware/baseModel");
const wxPaySerivce = require("../service/wx_pay");
// const orderService = require("../service/order");
const sysConfigSerivce = require("../service/sys_config");
const logsUtil = require("../../tool/logs");
const config = require("../../config/config");

const OrderAttach = config.orderAttach;

module.exports = {
    "POST /wx_pay/unifiedOrder": async(ctx, next) => {
        let order_id = ctx.get("order_id");
        let userId = ctx.getPappletUserId();
        let ip = ctx.ip;

        let orderRow = await order.findOne({
            where: { id: order_id },
            include: [{
                association: order.associations.dtl,
                attributes: ["id", "good_desc"],
            }, ],
        });

        if (!orderRow) {
            return ctx.fail("订单不存在");
        }

        let { order_sn, actual_price: total_fee } = orderRow;

        let good_desc = orderRow.dtl[0].good_desc;
        let userInfo = await user.findOne({ where: { id: userId } });
        if (!userInfo) {
            return ctx.fail("请重新登录");
        }
        let openid = userInfo.weixin_openid;
        let attach = JSON.stringify({ type: OrderAttach.order });
        let wxRow = await wxPaySerivce.createUnifiedOrder({ good_desc, openid, order_sn, total_fee, ip, attach });
        if (wxRow.result_code === "SUCCESS") {
            return ctx.success(wxRow);
        } else {
            return ctx.fail(wxRow.err_code_des);
        }
    },
    // 用户 激活 下单
    "POST /wx_pay/userActivate": async(ctx, next) => {
        let userId = ctx.getPappletUserId();
        let activate_sn = ctx.get("activate_sn");

        let ip = ctx.ip;

        let userInfo = await user.findOne({ where: { id: userId } });
        if (!userInfo) {
            return ctx.fail("请重新登录");
        }
        let openid = userInfo.weixin_openid;
        let good_desc = "用户激活";
        let total_fee = await sysConfigSerivce.getAccountActivation();
        let attach = JSON.stringify({ type: OrderAttach.activate });
        let wxRow = await wxPaySerivce.createUnifiedOrder({ good_desc, openid, order_sn: activate_sn, total_fee, ip, attach });

        if (wxRow.result_code === "SUCCESS") {
            return ctx.success(wxRow);
        } else {
            return ctx.fail(wxRow.err_code_des);
        }
    },

    // vip充值 下单
    "POST /wx_pay/userVipRecharge": async(ctx, next) => {
        let recharge_sn = ctx.get("recharge_sn");
        let userId = ctx.getPappletUserId();
        let ip = ctx.ip;

        let userInfo = await user.findOne({ where: { id: userId } });
        if (!userInfo) {
            return ctx.fail("请重新登录");
        }

        let userNoteRechargeRow = await user_note_recharge.findOne({ where: { recharge_sn: recharge_sn } });
        if (!userNoteRechargeRow) {
            return ctx.fail("充值单号验证错误");
        }

        let total_fee = userNoteRechargeRow.total_fee;

        let openid = userInfo.weixin_openid;
        let good_desc = "提升会员等级充值";

        let attach = JSON.stringify({ type: OrderAttach.recharge });
        let wxRow = await wxPaySerivce.createUnifiedOrder({ good_desc, openid, order_sn: recharge_sn, total_fee, ip, attach });
        if (wxRow.result_code === "SUCCESS") {
            return ctx.success(wxRow);
        } else {
            return ctx.fail(wxRow.err_code_des);
        }
    },

    "POST /wx_pay/notify": async(ctx, next) => {
        try {
            let result = await ctx.getXml();
            // let result = ctx.getBody()

            logsUtil.log("notify-result:" + JSON.stringify(result));
            if (result.result_code === "SUCCESS") {
                let { out_trade_no, attach, transaction_id } = result;
                let { type, grade_id } = JSON.parse(decodeURIComponent(attach));
                // 购买商品订单
                if (type === OrderAttach.order) {
                    // let isSuccess = await orderService.notifyBuyOrder(out_trade_no, 1, transaction_id);
                    // if (isSuccess) {
                    //     return ctx.jsonToXml("SUCCESS", "OK");
                    // }
                }

                // vip充值订单
                else if (type === OrderAttach.recharge) {
                    // let isSuccess = await orderService.notifyVipRecharge(out_trade_no, grade_id);
                    // if (isSuccess) {
                    //     return ctx.jsonToXml("SUCCESS", "OK");
                    // }
                }
            }
            return ctx.jsonToXml("ERROR", "失败");
        } catch (e) {
            logsUtil.ctxError(e, ctx);
            return ctx.jsonToXml("ERROR", "失败");
        }
    },

    "POST /wx_pay/refund": async(ctx, next) => {
        logsUtil.log("notify-refund: 退款回调" + JSON.stringify(ctx));
    },
};